package vip.ola.pay.channel.daifuchannel.newbaolong;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.channel.BaseTrans;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import static vip.ola.core.common.constant.PayEnum.ERR_0121;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@Service
public class NewblongTransService extends BaseTrans {

    private static final MyLog _log = MyLog.getLog(NewblongTransService.class);

    @Override
    public String getChannelName() {
        return PayConstant.CHANNEL_NAME_ALIPAY;
    }

    public JSONObject trans(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        try {
            _log.info("代付转账：" + transOrder.getChannelMchId());
            AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(transOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String orderId = transOrder.getTransOrderId();
            String payUrl = accountParams.getString("payUrl");
            String privateKey = accountParams.getString("privateKey");
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("cardName", transOrder.getAccountName().trim());
            obj.put("cardNum", transOrder.getAccountNo().trim());
            obj.put("amt", String.valueOf(transOrder.getAmount()));
            obj.put("merId", mchId);
            obj.put("transTime", df.format(new Date()));
            obj.put("transType", "DF_CARD");
            obj.put("bankName", transOrder.getBankName());
            obj.put("notifyUrl", accountParams.getString("notify_url"));
            obj.put("orderNo", orderId);
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            String sign = sign(paramsrc,privateKey);
            obj.put("sign", sign);
            _log.info("下单请求url={}，param={},json->{}",payUrl,obj,JSONObject.toJSONString(obj));
            String respData = call(payUrl,obj);
            _log.info("下单结束respData->{}",respData);
            if (StringUtils.isNotEmpty(respData)){
                JSONObject jsonObject = JSONObject.parseObject(respData);
                retObj.put("transOrderId", transOrder.getTransOrderId());
                if (jsonObject != null){
                    String code = jsonObject.getString("respCode");
                    if ("0000".equals(code) || "0001".equals(code) ){
                        retObj.put("status",1);
                    }else {
                        retObj.put("status",3);
                        retObj.put("channelErrCode", code);
                        retObj.put("channelErrCode", jsonObject.getString("respDesc"));
                    }
                }
            }else {
                retObj.put("status",3);
                retObj.put("channelErrCode", "上游系统异常，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            retObj.put("status",3);
            retObj.put("channelErrCode", e.getMessage());
        }
        return  retObj;
    }


    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }




    private static String sign(String paramSrc, String privateKey) {
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramSrc + privateKey);
        String sign = null;
        try {
            sign = PayDigestUtil.md5(strbuff.toString(), "UTF-8");
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }


    public JSONObject query(TransOrder transOrder) {
        return  null;
    }



    @Override
    public JSONObject balance(String payParam) {
        JSONObject accountParams = JSONObject.parseObject(payParam);
        String mchId = "9988500034";
        String privateKey = accountParams.getString("privateKey");
        String balanceUrl = accountParams.getString("balanceUrl");
        TreeMap<String, String> obj = new TreeMap<String, String>();
        obj.put("merId", mchId);
        obj.put("tranType", "queryBalance");
        // 生成签名
        StringBuffer paramstr = new StringBuffer();
        for (String pkey : obj.keySet()) {
            String pvalue = obj.get(pkey);
            if (pvalue != null && pvalue != "") {
                paramstr.append(pkey + "=" + pvalue + "&");
            }
        }
        String paramsrc = paramstr.substring(0, paramstr.length() - 1);
        String sign = sign(paramsrc,privateKey);
        obj.put("sign", sign);
        _log.info("余额查询请求url={}，param={},json->{}",balanceUrl,obj,JSONObject.toJSONString(obj));
        String respData = call(balanceUrl,obj);
        _log.info("下单结束respData->{}",respData);
        if (StringUtils.isNotEmpty(respData)){
            JSONObject jsonObject = JSONObject.parseObject(respData);
            if (jsonObject != null){
                String code = jsonObject.getString("respCode");
                if ("0000".equals(code)  ){
                    String totalAmt = jsonObject.getString("totalAmt");
                    JSONObject result = new JSONObject();
                    result.put("retCode","SUCCESS");
                    result.put("cashBalance",totalAmt);
                    return result;
                }
            }
        }
        return null;
    }



    public static void main (String args[]){
    }


}
